# _*_ utf-8 _*_
__author__ = "LiuJian"
__date__ = "2021/7/23 0023 13:45"

# @FileName :DataBase.py

import pymysql
from Melon.Module.dbInfo import dbinfo


class DataBase(object):

    def __init__(self, host=dbinfo['host'], user=dbinfo['user'], password=dbinfo['password'], port=dbinfo['port'],
                 database=dbinfo['database'], charset=dbinfo['charset']):
        self.host = host
        self.user = user
        self.password = password
        self.port = port
        self.database = database
        self.charset = charset

    def __create_conn(self):
        if not self.database:
            raise RuntimeError('没有找到数据库！！！')
        try:
            self.conn = pymysql.connect(host=self.host,
                                        user=self.user,
                                        password=self.password,
                                        port=self.port,
                                        database=self.database,
                                        charset=self.charset)
        except Exception as e:
            raise RuntimeError('数据库配置错误:%s', e)

        return self.conn

    def __execute_sql(self, sql, params=None):
        try:
            # 获取游标
            self.cur = self.__create_conn().cursor(cursor=pymysql.cursors.DictCursor)
            print(self.cur)
            self.cur.execute(sql, params)
            # 事务提交
            self.conn.commit()
            print('提交成功！！！')
        except Exception as e:
            # 事务回滚
            self.conn.rollback()
            raise RuntimeError('执行sql异常：', e)

    def __close_sql(self):
        try:
            if self.cur:
                print(self.cur)
                self.cur.close()
        except Exception as e:
            raise RuntimeError('关闭游标异常：', e)

    def check_sql(self, sql, params=None):
        self.__execute_sql(sql, params)
        data = self.cur.fetchall()
        self.__close_sql()
        return data


if __name__ == "__main__":
    # db1 = DataBase(host='49.233.39.160', user='user', password="leboAa!#$123", database='lebo', port=3306,
    #                charset='utf8')
    db1 = DataBase()
    sql = "select * from melon where uname = %s"
    print(db1.check_sql(sql, '小刘'))
